package com.zt.sso.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

public class SsoCheck {

	/**
	 * 获得cookies里面的指定key的值
	 * 
	 * @param request
	 *            请求对象
	 * @param response
	 *            响应对象
	 * @param keyStr
	 *            需要获得值的键
	 * @return 指定key的值
	 */
	public static String getCookiesValues(HttpServletRequest request, HttpServletResponse response, String keyStr) {
		String valStr = null;
		String cookieVal = null;
		Cookie[] cookies = request.getCookies();
		String requestVal = request.getParameter(keyStr);
		if (null != cookies && cookies.length > 1) {
			for (Cookie cookie : cookies) {
				if (keyStr.equals(cookie.getName())) {
					// log.info("OLD
					// cookieVal:"+cookieVal+",requestVal:"+requestVal);
					if (null != requestVal && !"".equals(requestVal)) {
						// 所取值不为空
						requestVal = decodeVal(requestVal);
						cookie.setValue(requestVal);
						cookie.setPath("/");
						response.addCookie(cookie);
					}
					cookieVal = cookie.getValue();
					// log.info("NEW
					// cookieVal:"+cookieVal+",requestVal:"+requestVal);
					valStr = cookieVal;
					break;
				}
			}
		} else {
			valStr = request.getParameter(keyStr);
			if (StringUtils.isNotBlank(requestVal)) {
				valStr = decodeVal(valStr);
			}
			if (!"".equals(valStr)) {
				setCookie(response, keyStr, valStr, -1);
			}
		}

		return valStr;
	}

	/**
	 * 获得cookies里面的指定key的值 如果没有取默认值
	 * 
	 * @param request
	 *            请求对象
	 * @param keyStr
	 *            需要获得值的键
	 * @param defultVal
	 *            默认值
	 * @return 指定key的值
	 */
	public static String getCookiesValues(HttpServletRequest request, String keyStr, String defultVal) {
		String reStr = getCookiesValues(request, keyStr);
		if ("".equals(reStr) || null == reStr) {
			reStr = defultVal;
		}
		return reStr;
	}

	/**
	 * 获得cookies里面的指定key的值
	 * 
	 * @param request
	 *            请求对象
	 * @param keyStr
	 *            需要获得值的键
	 * @return 指定key的值
	 */
	public static String getCookiesValues(HttpServletRequest request, String keyStr) {
		String valStr = null;
		String cookieVal = null;
		Cookie[] cookies = request.getCookies();
		if (null != cookies && cookies.length > 1) {
			for (Cookie cookie : cookies) {
				if (keyStr.equals(cookie.getName())) {

					cookieVal = cookie.getValue();
					cookie.setPath("/");
					valStr = cookieVal;
					break;
				}
			}
		} else {
			if (StringUtils.isNotBlank(request.getParameter(keyStr))) {
				valStr = request.getParameter(keyStr);

			}
		}
		valStr = decodeVal(valStr);
		return valStr;
	}

	/**
	 * 设置cookie
	 * 
	 * @param response
	 *            响应对象
	 * @param keyStr
	 *            需要设置的键
	 * @param valStr
	 *            需要设置的值
	 * @param maxAgeInSeconds
	 *            超时时间 （-1为浏览器生命周期，0为销毁当前）
	 */
	public static void setCookie(HttpServletResponse response, String keyStr, String valStr, int maxAgeInSeconds) {
		Cookie cookie = new Cookie(keyStr, valStr);
		cookie.setPath("/");// 跨端口
		cookie.setMaxAge(maxAgeInSeconds);// 设置超时
		response.addCookie(cookie);
	}

	/**
	 * 删除cookie
	 * 
	 * @param response
	 * @param keyStr
	 */
	private static void removeCookie(HttpServletResponse response, String keyStr) {
		setCookie(response, keyStr, "", 0);
	}

	/**
	 * 获得中文
	 * 
	 * @param val
	 * @return
	 */
	public static String decodeVal(String val) {
		String result = "";
		if (StringUtils.isNotBlank(val)) {
			try {
				result = URLDecoder.decode(val, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 验证用户id和token是否有效，如有效续时
	 * 
	 * @param userId
	 *            用户编号
	 * @param userType
	 *            用户类型
	 * @param token
	 *            用户登录门票
	 * @return
	 */
	public static boolean checkToken(String userId, String userType, String token) {
		// 效验状态
		boolean reStatus = false;
		String ckTokenKey = SsoRedisManager.getSsoRedis(token, null);
		String tokenKey = userType + "$" + userId;


		if (null != ckTokenKey && tokenKey.equals(ckTokenKey)) {
			// 续时用户登录成功标识
			if (SsoRedisManager.setSsoRedisByMs(token, tokenKey, 3600)) {
				// 检测唯一登录开关是否开启
				String isOnlyLoginStr = SsoRedisManager.getSsoRedis("isOnlyLogin", null);
				// 唯一登录开关
				boolean isOnlyLogin = (StringUtils.isBlank(isOnlyLoginStr) ? false
						: ("1".equals(isOnlyLoginStr) ? true : false));

				if (isOnlyLogin) {
					// 设置唯一登录标识
					SsoRedisManager.setSsoRedisByMs(userId, token, 3600);
				}
				reStatus = true;
			} 
		} 
		return reStatus;
	}

}
